package com.cy.pj.common.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Order(2)
@Aspect
@Component
public class SysCacheAspect {
    private Map cache  = new ConcurrentHashMap();
    @Pointcut("@annotation(com.cy.pj.common.annotation.RequiredCache)")
    public void doCache(){}
    @Pointcut("@annotation(com.cy.pj.common.annotation.ClearCache)")
    public void doClearCache(){}
    @AfterReturning("doClearCache()")
    public void doAfterReturning(){
        System.out.println("clear cache");
        cache.clear();

    }
    @Around("doCache()")
    public Object doCacheAround(ProceedingJoinPoint jp) throws Throwable{
        //cache中去数据
        System.out.println("Get Data From cache");
        Object result = cache.get("cacheKey");//这里cacheKey后期会做一个设计
        if (result != null)
            return result;
        //cache中从数据库去取
        result = jp.proceed();
        //cache 清楚缓存
        System.out.println("put data to cache");
        cache.put("cacheKey",result);
        return result;
    }
}
